package com.woniuxy.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.exception.CartException;
import com.woniuxy.commons.exception.OrderException;
import com.woniuxy.commons.exception.code.CartExceptionCode;
import com.woniuxy.commons.exception.code.OrderExceptionCode;
import com.woniuxy.commons.utils.BeanCopyUtil;
import com.woniuxy.commons.utils.CommonsUtil;
import com.woniuxy.commons.utils.DateUtil;
import com.woniuxy.controller.form.*;
import com.woniuxy.dao.model.*;
import com.woniuxy.dao.DietOrderDao;
import com.woniuxy.service.CartInfoService;
import com.woniuxy.service.DietOrderFoodService;
import com.woniuxy.service.DietOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.service.dto.*;
import org.springframework.beans.factory.wiring.BeanWiringInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.transform.Templates;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author psy
 * @since 2022-06-28
 */
@Service
public class DietOrderServiceImpl
        extends ServiceImpl<DietOrderDao, DietOrder> implements DietOrderService {

    @Resource
    private DietOrderService dietOrderService;
    @Resource
    private DietOrderFoodService dietOrderFoodService;
    @Resource
    private RedisTemplate<String,String> sot;
    @Resource
    private CartInfoService cartInfoService;
    @Override
    public boolean addOrder(CreateOrderForm createOrderForm) {
        DietOrder dietOrder = BeanCopyUtil.copyOne(createOrderForm, DietOrder.class);
        boolean save = dietOrderService.save(dietOrder);
        if(save){
            return true;
        }else{
          throw new OrderException(OrderExceptionCode.ORDER_ADD_FAIL.getCode(),OrderExceptionCode.ORDER_ADD_FAIL.getMessage());
        }
    }

    @Override
    public boolean updateOrderByPayFinish(PayFinishForm payFinishForm) {
        DietOrder dietOrder = BeanCopyUtil.copyOne(payFinishForm, DietOrder.class);
        boolean b = dietOrderService.saveOrUpdate(dietOrder);
        if(b){
            return true;
        }else{
            throw new OrderException(OrderExceptionCode.ORDER_UPDATE_FAIL_PAYFINASH.getCode(),OrderExceptionCode.ORDER_UPDATE_FAIL_PAYFINASH.getMessage());
        }
    }

    @Override
    public boolean storeAcceptOrder(StoreAcceptOrderForm acceptOrderForm) {
        DietOrder dietOrder = BeanCopyUtil.copyOne(acceptOrderForm, DietOrder.class);
        boolean b = dietOrderService.saveOrUpdate(dietOrder);
        if(b){
            return true;
        }else{
            throw new OrderException(OrderExceptionCode.ORDER_STOREACCEPT_UPDATE_FAIL.getCode(),OrderExceptionCode.ORDER_STOREACCEPT_UPDATE_FAIL.getMessage());

        }
    }

    @Override
    public boolean buycancelorder(String orderNum) {
        String format1 = CommonsUtil.getOrderCreateTime();
        boolean update = dietOrderService.update(new UpdateWrapper<DietOrder>().eq("orderNum", orderNum).set("state", 5).set("cancelDate",format1));
        if(update){
            return true;
        }else {
            throw new OrderException(OrderExceptionCode.ORDER_BUYCANCEL_FAIL.getCode(),OrderExceptionCode.ORDER_BUYCANCEL_FAIL.getMessage());

        }
    }

    @Override
    public boolean storeDispatching(StoreDispatchingForm storeDispatchingForm) {
        DietOrder dietOrder = BeanCopyUtil.copyOne(storeDispatchingForm, DietOrder.class);
        dietOrder.setState(3);
        boolean b = dietOrderService.saveOrUpdate(dietOrder);
        if(b){
            return true;
        }else{
            throw new OrderException(OrderExceptionCode.ORDER_STORE_DISPATCHING_FAIL.getCode(),OrderExceptionCode.ORDER_STORE_DISPATCHING_FAIL.getMessage());

        }
    }

    @Override
    public boolean storeRefuse(String orderNum,String operReason) {
        boolean update = dietOrderService.update(new UpdateWrapper<DietOrder>().eq("orderNum", orderNum).set("refuseReason", operReason).set("state", 7));
        if(update){
            return true;
        }else{
            throw new OrderException(OrderExceptionCode.ORDER_STORE_REFUSE_FAIL.getCode(),OrderExceptionCode.ORDER_STORE_REFUSE_FAIL.getMessage());
        }
    }

    @Override
    public boolean conrierRefuse(String orderNum, String deliveryRefuseReason) {
        boolean update = dietOrderService.update(new UpdateWrapper<DietOrder>().eq("orderNum", orderNum).set("state", 8).set("deliveryRefuseReason", deliveryRefuseReason));
        if(update){
            return true;
        }else{
            throw new OrderException(OrderExceptionCode.ORDER_COURIER_REFUSE_FAIL.getCode(),OrderExceptionCode.ORDER_COURIER_REFUSE_FAIL.getMessage());
        }

    }

    @Override
    public boolean waitDispatching(String orderNum) {
        boolean update = dietOrderService.update(new UpdateWrapper<DietOrder>().eq("orderNum", orderNum).set("state", 6));
        if(update){
            return true;
        }else{
            throw new OrderException(OrderExceptionCode.ORDER_STORE_WAITDISPATCHING_FAIL.getCode(),OrderExceptionCode.ORDER_STORE_WAITDISPATCHING_FAIL.getMessage());

        }
    }

    @Override
    public boolean finishOrder(String orderNum) {
        String format1 = CommonsUtil.getOrderCreateTime();
        boolean update = dietOrderService.update(new UpdateWrapper<DietOrder>().eq("orderNum", orderNum).set("reachDate", format1)
                .set("evaluate", 0).set("state", 4));
        if(update){
            return true;
        }else{
            throw new OrderException(OrderExceptionCode.ORDER_FINISH_FAIL.getCode(),OrderExceptionCode.ORDER_FINISH_FAIL.getMessage());
        }
    }

    @Override
    public Page<OrderCustomerDto> getOrderByCustomerId(OrderCustomerLookForm orderCustomerLookForm) {
        Page<DietOrder> page = new Page<>(orderCustomerLookForm.getPageNum(),orderCustomerLookForm.getPageSize());
        Page<DietOrder> orderPage = dietOrderService.page(page, new QueryWrapper<DietOrder>().eq("customerId",orderCustomerLookForm.getCustomerId()));
        if(null==orderPage.getRecords()){
            return null;
        }
        //判断有没有条件查询
        if(null==orderCustomerLookForm.getDay()||0==orderCustomerLookForm.getDay()){
            Page<OrderCustomerDto> orderCustomerDtoPage = BeanCopyUtil.copyPageInfo(orderPage, OrderCustomerDto.class);
            return orderCustomerDtoPage;
        }
        Integer day = orderCustomerLookForm.getDay();
        long l = System.currentTimeMillis();
        Long dayTime=day*24*60*60*1000L;
        Long oldTime=l-dayTime;
        String s = DateUtil.parseDateLong(oldTime, "yyyy-MM-dd HH:mm:ss");
        Page<DietOrder> customerId = dietOrderService.page(page, new QueryWrapper<DietOrder>().eq("customerId", orderCustomerLookForm.getCustomerId())
                .apply("UNIX_TIMESTAMP(orderDate)>=UNIX_TIMESTAMP('" + s + "')"));
        if(null==customerId.getRecords()){
            return null;
        }
        Page<OrderCustomerDto> orderCustomerDtoPage = BeanCopyUtil.copyPageInfo(customerId, OrderCustomerDto.class);
        return orderCustomerDtoPage;
    }

    @Override
    public OrderDetailsDto getOrderDetailsByOrderNum(String orderNum,String storeName) throws JsonProcessingException {
//        DietOrder dietOrder = dietOrderService.getById(orderNum);
        DietOrder dietOrder = dietOrderService.getOne(new QueryWrapper<DietOrder>().eq("orderNum", orderNum));
        ArrayList<DietOrderFood> dietOrderFood = (ArrayList<DietOrderFood>)dietOrderFoodService.list(new QueryWrapper<DietOrderFood>().eq("orderNum", orderNum));
        OrderDetailsDto orderDetailsDto = BeanCopyUtil.copyOne(dietOrder, OrderDetailsDto.class);
        ArrayList<OrderDetailsFoodsDto> orderDetailsFoodsDtos = (ArrayList<OrderDetailsFoodsDto>)BeanCopyUtil.copyList(dietOrderFood, OrderDetailsFoodsDto.class);
        orderDetailsDto.setOrderDetailsFoodsDtos(orderDetailsFoodsDtos);
        //测试redis中存入商家信息
        TestRedisForm test=new TestRedisForm();
        ObjectMapper om=new ObjectMapper();
        String s = om.writeValueAsString(test);
        sot.opsForValue().set(storeName,s);

        String store = (String)sot.opsForValue().get(storeName);
        StoreInfo storeInfo = JSON.parseObject(store, StoreInfo.class);
        Double price = dietOrder.getPrice();
        double minTotal=0;
        for (DietOrderFood orderFood : dietOrderFood) {
            minTotal+=orderFood.getCount()*orderFood.getPrice();
        }
        Double dphPrice = storeInfo.getDphPrice();
        double packingPrice=price-minTotal-dphPrice;
        orderDetailsDto.setPackingPrice(packingPrice);
        orderDetailsDto.setDphPrice(dphPrice);
        return orderDetailsDto;
    }

    @Override
    public Page<OrderStoreDto> getOrderByStoreId(OrderStoreLookForm orderStoreLookForm) {
        Page<DietOrder> page = new Page<>(orderStoreLookForm.getPageNum(),orderStoreLookForm.getPageSize());
        //默认仅按照商家ID查询
        Page<DietOrder> storeId = dietOrderService.page(page, new QueryWrapper<DietOrder>().eq("storeId", orderStoreLookForm.getStoreId()));
        if(null==storeId.getRecords()){
            return null;
        }else {
            //条件查询
            if (null != orderStoreLookForm.getState()) {
                Page<DietOrder> page1 = dietOrderService.page(page, new QueryWrapper<DietOrder>().eq("storeId", orderStoreLookForm.getStoreId())
                        .eq("state", orderStoreLookForm.getState()));
                if (null == page1.getRecords()) {
                    return null;
                }
                if (null != orderStoreLookForm.getText() && !"".equals(orderStoreLookForm.getText())) {
                    Page<DietOrder> page2 = dietOrderService.page(page, new QueryWrapper<DietOrder>().eq("storeId", orderStoreLookForm.getStoreId())
                            .eq("state", orderStoreLookForm.getState())
                            .like("orderUser", orderStoreLookForm.getText()).or().like("orderPhone", orderStoreLookForm.getText()));
                    if (null == page2.getRecords()) {
                        return null;
                    }
                    Page<OrderStoreDto> orderStoreDtoPage = BeanCopyUtil.copyPageInfo(page2, OrderStoreDto.class);
                    return orderStoreDtoPage;
                }
                Page<OrderStoreDto> orderStoreDtoPage = BeanCopyUtil.copyPageInfo(page1, OrderStoreDto.class);

                return orderStoreDtoPage;
            } else {
                //模糊查询（暂时支持订餐人和订餐电话的模糊查询）
                if (null != orderStoreLookForm.getText() && !"".equals(orderStoreLookForm.getText())) {
                    Page<DietOrder> page1 = dietOrderService.page(page, new QueryWrapper<DietOrder>().eq("storeId", orderStoreLookForm.getStoreId()).like("orderUser", orderStoreLookForm.getText()).or().like("orderPhone", orderStoreLookForm.getText()));
                    if (null == page1.getRecords()) {
                        return null;
                    }
                    Page<OrderStoreDto> orderStoreDtoPage = BeanCopyUtil.copyPageInfo(page1, OrderStoreDto.class);
                    return orderStoreDtoPage;
                }
            }
            Page<OrderStoreDto> orderStoreDtoPage = BeanCopyUtil.copyPageInfo(storeId, OrderStoreDto.class);
            return orderStoreDtoPage;
        }
    }

    @Override
    public AllCartListDto orderAgain(Long id, String orderNum, String storeName) {
        AllCartListDto allCartListDto=new AllCartListDto();
        DietOrderFood dietOrderFood = dietOrderFoodService.getOne(new QueryWrapper<DietOrderFood>().eq("orderNum", orderNum));
        allCartListDto.setPrice(dietOrderFood.getPrice());
        allCartListDto.setNum(dietOrderFood.getCount());
        allCartListDto.setFoodName(dietOrderFood.getFoodName());
        String store = (String)sot.opsForValue().get(storeName);
        StoreInfo storeInfo = JSON.parseObject(store, StoreInfo.class);
        Double packingPrice = storeInfo.getPackingPrice();
        Double dphPrice = storeInfo.getDphPrice();
        allCartListDto.setPackingPrice(packingPrice);
        allCartListDto.setDphPrice(dphPrice);
        allCartListDto.setStoreName(storeName);
        CartInfo cartInfo = BeanCopyUtil.copyOne(allCartListDto, CartInfo.class);
        cartInfo.setCustomerId(id);
        boolean save = cartInfoService.save(cartInfo);
        if(save){
            return allCartListDto;
        }else{
            throw new CartException(CartExceptionCode.CART_ADD_FAIL.getCode(),CartExceptionCode.CART_ADD_FAIL.getMessage());
        }
    }
}
